package com.red.servlet.house;

import com.red.entity.House;
import com.red.service.impl.HouseServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "HouseAUServlet", value = "/house-ua")

public class HouseAUServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String mode = req.getParameter("mode");
        Integer house_id = Integer.valueOf(req.getParameter("house_id"));
        String house_name = req.getParameter("house_name");
        int price = Integer.parseInt(req.getParameter("price"));
        String[] address = req.getParameter("address").split(",");
        String detailed_address = req.getParameter("detailed_address");
        String description = req.getParameter("description");

        House house = new House();

        house.setHouse_id(house_id);
        house.setHouse_name(house_name);
        house.setPrice(price);

        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < address.length; i++) {
            stringBuilder.append(address[i]);
            if (i < address.length - 1)
                stringBuilder.append(',');
        }

        house.setAddress(stringBuilder.toString());
        house.setDetailed_address(detailed_address);
        house.setDescription(description);


        if (mode.equals("1")) {
            if (new HouseServiceImpl().addHouse(house)) {
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().print("添加成功");
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print("添加失败");
            }
        } else if (mode.equals("2")) {
            if (house.getHouse_id() != null) {
                if (new HouseServiceImpl().updateHouse(house)) {
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().print("修改成功");
                } else {
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    resp.getWriter().print("修改失败");
                }
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print("缺少ID");
            }
        } else
            resp.getWriter().print("mode参数不符合要求");
    }
}
